﻿using System.Text.Json;

using Microsoft.AspNetCore.DataProtection.KeyManagement;
using Microsoft.AspNetCore.StaticFiles;

using XServer.Managers;
using XServer.Models.OSS;
using XServer.Utility.Pools;

namespace XServer.Utility
{
    public static class CommonTools
    {
        /// <summary>
        /// 获取文件MIME
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public static string GetMimeType(string file)
        {
            var provider = new FileExtensionContentTypeProvider();
            if (provider.TryGetContentType(file, out var mimeType))
            {
                return mimeType;
            }
            return "application/octet-stream"; // 默认类型
        }

        #region OSS

        /// <summary>
        /// 获取文件
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public static string GetFile(string file, ILogger logger)
        {
            string dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "images");
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "images", file);

            // 服务器中有文件缓存
            if (System.IO.File.Exists(filePath))
            {
                return filePath;
            }

            // 文件不存在，从OSS上获取
            PictureDownloadPoolTask task = new PictureDownloadPoolTask(file, logger);
            var res = task.Execute();

            if (!res)
            {
                return "Error";
            }

            return filePath;
        }

        /// <summary>
        /// 判断文件是否存在
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public static bool FileExist(string file)
        {
            string dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "images");
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "images", file);
            if (System.IO.File.Exists(filePath))
            {
                return true;
            }

            return OssManager.Instance.CheckFileExist(filePath);
        }

        /// <summary>
        /// 上传文件到OSS
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public static bool UploadFile(string file, ILogger logger)
        {
            //_logger.LogInformation($"上传文件: {file}");
            PictureUploadPoolTask task = new PictureUploadPoolTask(file, logger);
            var res = task.Execute();

            if (!res)
            {
                return false;
            }
            return true;
        }

        #endregion
    }
}
